package cn.usian.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.usian.common.ResultEnum;
import cn.usian.dto.UserDto;
import cn.usian.mapper.UserMapper;
import cn.usian.common.Results;
import cn.usian.pojo.User;
import cn.usian.service.UserService;
import cn.usian.utlis.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public Results login(User user) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getUsername,user.getUsername());
        User users = this.baseMapper.selectOne(qw);
        if (users==null){
            return Results.build(null,ResultEnum.LOGIN_PASSWORD_ERROR);
        }
        if (!users.getPassword().equals(user.getPassword())){
            return Results.build(null,ResultEnum.LOGIN_PASSWORD_ERROR);
        }
        if (users.getIsDeleted()==1){
            return Results.build(null,ResultEnum.LOGIN_ISDELETE_ERROR);
        }
        String token = setToken(users);
        return Results.build(token, ResultEnum.SUCCESS);
    }

    @Override
    public Results LoginCode(String phone,Integer status) {
        extracted(phone,status);
        return Results.build(null, ResultEnum.SUCCESS);

    }



    @Override
    public Results toLoginCode(UserDto userDto) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, userDto.getPhone());
        User user = this.baseMapper.selectOne(qw);
        String redisCode = redisTemplate.boundValueOps("CodeLogin:" + userDto.getPhone()).get();
        if (user==null){
            return Results.build(null,ResultEnum.LOGIN_USER_ERROR);
        }
        if (!userDto.getCode().equals(redisCode)){
            return Results.build(null,ResultEnum.LOGIN_CODE_ERROR);
        }
        String token = setToken(user);
        return Results.build(token, ResultEnum.SUCCESS);
    }



    @Override
    public Results toRegister(UserDto userDto) {
        String code =redisTemplate.boundValueOps("RegisterLogin:" + userDto.getPhone()).get();
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,userDto.getPhone());
        List<User> users = this.baseMapper.selectList(qw);
        if (users.size()>0){
            return Results.build(null,ResultEnum.LOGIN_PHONE_ERROR);
        }
        if (!userDto.getCode().equals(code)){
           return Results.build(null,ResultEnum.LOGIN_CODE_ERROR);
        }
        User user = new User(userDto.getPhone()+"",userDto.getPassword(),3,null,userDto.getPhone());
        user.setIsDeleted(0);
        this.baseMapper.insert(user);
        return Results.build(null,ResultEnum.SUCCESS);
    }

    @Override
    public Results toUpdatPws(UserDto userDto) {
        String code =redisTemplate.boundValueOps("UpPwdLogin:" + userDto.getPhone()).get();
        if (!userDto.getCode().equals(code)){
            return Results.build(null,ResultEnum.LOGIN_CODE_ERROR);
        }
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,userDto.getPhone());
        User users = this.baseMapper.selectOne(qw);
        if (users==null){
            return Results.build(null,ResultEnum.LOGIN_USER_ERROR);
        }
        users.setPassword(userDto.getPassword());
        this.baseMapper.updateById(users);
        return Results.build(null,ResultEnum.SUCCESS);
    }

    @Override
    public Results findUserType() {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getType,2);

        return Results.build(this.baseMapper.selectList(qw),ResultEnum.SUCCESS);
    }

    @Override
    public Long findUserName(String username) {
        return this.baseMapper.seleByName(username);
    }


    public void extracted(String phone,Integer status) {
        String host = "https://smkjdxtzjk.market.alicloudapi.com";
        String path = "/standard/sms/send";
        String method = "POST";
        String appcode = "851ce02924664c50b6fd03f4196b4b07";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        int radom = RandomUtil.randomInt(0000, 9999);
        if (status==1){
            redisTemplate.boundValueOps("CodeLogin:"+ phone).set(radom+"",300, TimeUnit.SECONDS);
        }
        if (status==2){
            redisTemplate.boundValueOps("RegisterLogin:"+ phone).set(radom+"",300, TimeUnit.SECONDS);
        }
        if (status==3){
            redisTemplate.boundValueOps("UpPwdLogin:"+ phone).set(radom+"",300, TimeUnit.SECONDS);
        }


        bodys.put("templateId", "【智能云】您的验证码是"+radom+"。如非本人操作，请忽略本短信");
        bodys.put("receive", phone);
        bodys.put("tag", "tag");

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String setToken(User user) {
        String token = UUID.randomUUID().toString();
        redisTemplate.boundValueOps(token).set(JSON.toJSONString(user));
        return token;
    }


}
